import { download } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";
import router from "/@/router/index";
import { storageLocal } from "/@/utils/storage";

const FileTypes = {
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  pdf: "application/pdf",
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg"
};

export const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

export const handlePreview = file => {
  console.log(file, "file");
  if (file?.response?.code !== 200 || !file?.response?.data) return;
  download(file?.response?.data);
};

export const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);
  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);

    router.push("/login");
    storageLocal.removeItem("info");
  }
};

export const beforeAvatarUpload = file => {
  // const type = file.type.slice(file.type.lastIndexOf("/") + 1);
  const type = file.name.substring(file.name.lastIndexOf(".") + 1);
  if (!Object.keys(FileTypes).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(FileTypes).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};
